<template>
  <div>
    <SearchAndList>
      <!-- 搜索框 S -->
      <template #search>
        <el-form :inline="true" :model="searchForm">
          <el-form-item label="型号搜索：" size="medium">
            <el-input
              v-model="searchForm.vmType"
              placeholder="请输入"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              @click="searchTaskList(true)"
              size="medium"
              icon="el-icon-search"
              >查询</el-button
            >
          </el-form-item>
        </el-form>
      </template>
      <!-- 搜索框 E -->
      <!-- 列表开始 -->
      <template #list>
        <el-table
          v-loading="loading"
          :data="TypeData.currentPageRecords"
          style="width: 100%"
        >
          <!-- 序号 -->
          <el-table-column
            type="index"
            :index="getIndex"
            label="序号"
            width="80"
          />
          <!-- 型号名称 -->
          <el-table-column prop="name" label="型号名称" />
          <!-- 型号编码 -->
          <el-table-column prop="model" label="型号编码" />
          <!-- 设备图片 -->
          <el-table-column label="设备图片">
            <template slot-scope="scope">
              <span
                ><img
                  :src="scope.row.image"
                  style="
                    width: 24px;
                    height: 24px;
                    border-radius: 50%;
                    background: #f3f6fb;
                    border: 1px solid #f3f6fb;
                  "
              /></span>
            </template>
          </el-table-column>
          <!-- 货道行 -->
          <el-table-column prop="vmRow" label="货道行" />
          <!-- 货道列 -->
          <el-table-column prop="vmCol" label="货道列" />
          <!-- 设备容量 -->
          <el-table-column prop="channelMaxCapacity" label="设备容量" />
          <!-- 操作 -->
          <el-table-column label="操作" width="100">
            <template slot-scope="scope">
              <el-button
                @click.native.prevent="revampType(scope)"
                type="text"
                size="small"
                style="font-size: 14px"
              >
                修改
              </el-button>
              <el-button
                @click.native.prevent="delType(scope.row.typeId)"
                type="text"
                size="small"
                style="color: red; font-size: 14px"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </template>
      <!-- 列表结束 -->
      <!-- 按钮开始 -->
      <template #buttons>
        <el-button
          size="medium"
          icon="el-icon-circle-plus-outline"
          @click="addTypeClick"
          >新建</el-button
        >
      </template>
      <!-- 按钮结束 -->
      <!-- 底部分页开始 -->
      <template #bottom>
        <el-pagination
          @current-change="paginaTion"
          layout="slot, prev, next"
          :page-size="10"
          :total="getTotalCount"
          prev-text="上一页"
          next-text="下一页"
          background
          :hide-on-single-page="true"
        >
          <template>
            <div class="str">
              共{{ TypeData.totalCount }}条记录&nbsp;&nbsp;第
              {{ TypeData.pageIndex }}/{{ TypeData.totalPage }} 页
            </div>
          </template>
        </el-pagination>
      </template>
      <!-- 底部分页结束 -->
    </SearchAndList>
    <el-dialog
      :title="showType ? '修改' : '新建'"
      :visible.sync="dialogFormVisible"
      custom-class="dialog"
      @close = "cancel"
    >
      <el-form :model="TypeNewFrom" ref="dialogForm" :rules="Typerules">
        <el-form-item
          prop="name"
          label="型号名称："
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="TypeNewFrom.name"
            autocomplete="off"
            placeholder="请输入"
            maxlength="10"
            :show-word-limit="true"
          ></el-input>
        </el-form-item>
        <el-form-item
          prop="model"
          label="型号编码："
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="TypeNewFrom.model"
            autocomplete="off"
            placeholder="请输入（限制数字、字母、中划线、下划线）"
            type="text"
            maxlength="15"
            :show-word-limit="true"
          ></el-input>
        </el-form-item>
        <el-form-item
          prop="vmRow"
          label="货道行数："
          :label-width="formLabelWidth"
        >
          <el-input-number
            v-model="TypeNewFrom.vmRow"
            controls-position="right"
            :min="1"
            :max="10"
            placeholder="请输入"
            style="width: 100%"
          ></el-input-number>
        </el-form-item>
        <el-form-item
          prop="vmCol"
          label="货道列数："
          :label-width="formLabelWidth"
        >
          <el-input-number
            v-model="TypeNewFrom.vmCol"
            controls-position="right"
            :min="1"
            :max="10"
            placeholder="请输入"
            style="width: 100%"
          ></el-input-number>
        </el-form-item>
        <el-form-item
          prop="channelMaxCapacity"
          label="货道容量："
          :label-width="formLabelWidth"
        >
          <el-input-number
            v-model="TypeNewFrom.channelMaxCapacity"
            controls-position="right"
            :min="1"
            :max="10"
            placeholder="请输入"
            style="width: 100%"
          ></el-input-number>
        </el-form-item>
        <el-form-item
          prop="image"
          label="设备图片："
          :label-width="formLabelWidth"
        >
          <el-upload
            class="avatar-uploader"
            action="https://jsonplaceholder.typicode.com/posts/"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            :http-request="RequestImgType"
            ref="img"
          >
            <img
              v-if="TypeNewFrom.image"
              :src="TypeNewFrom.image"
              class="avatar"
            />
            <i v-else class="el-icon-upload2 avatar-uploader-icon"></i>
            <div
              class="el-upload__tip"
              slot="tip"
              style="font-size: 14px; color: #bac0cd"
            >
              支持扩展名：jpg、png，文件不得大于100kb
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitType">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getVmTypeSearch,
  updataImg,
  addVmType,
  ChangeVmTypeDetial,
  delVmType
} from '@/api/Equipment'
import SearchAndList from '@/components/SearchAndList.vue'
// import EquipmentIDialog from './components/EquipmentIDialog.vue'
export default {
  components: { SearchAndList },
  data () {
    return {
      // 加载状态
      loading: false,
      // 设备搜索框
      searchForm: {
        vmType: ''
      },
      // 获取的设备数据
      TypeData: {
        currentPageRecords: [], // table 渲染的数据
        pageIndex: 1, // 现在是第几页
        pageSize: 10, // 每一页有少条
        totalCount: 0, // 一共有多少条
        totalPage: 0 // 一共有多少页
      },
      TypeNewFrom: {
        name: '',
        model: '',
        vmRow: undefined,
        vmCol: undefined,
        channelMaxCapacity: undefined,
        image: ''
      },
      formLabelWidth: '100px',
      dialogFormVisible: false,
      showType: false,
      Typerules: {
        name: [
          { required: true, message: '请输入', trigger: 'submit' },
          { min: 1, max: 10 },
          {
            validator: (rule, value, callback) => {
              let isRepect = false
              if (!this.showType) {
                isRepect = this.TypeData.currentPageRecords.some(
                  (item) => item.name === value
                )
              } else {
                isRepect = this.TypeData.currentPageRecords.some(
                  (item) =>
                    item.name === value &&
                    item.typeId !== this.TypeNewFrom.typeId
                )
              }
              isRepect ? callback(new Error('该型号名称已存在')) : callback()
            },
            trigger: 'submit'
          }
        ],
        model: [
          { required: true, message: '请输入', trigger: 'submit' },
          { pattern: /^[a-zA-Z0-9-_]{1,15}$/, message: '请输入合法的型号编码' },
          {
            validator: (rule, value, callback) => {
              let isRepect = false
              if (!this.showType) {
                isRepect = this.TypeData.currentPageRecords.some(
                  (item) => item.model === value
                )
              } else {
                isRepect = this.TypeData.currentPageRecords.some(
                  (item) =>
                    item.model === value &&
                    item.typeId !== this.TypeNewFrom.typeId
                )
              }
              isRepect ? callback(new Error('型号编号已存在')) : callback()
            },
            trigger: 'submit'
          }
        ],
        vmRow: [{ required: true, message: '请输入', trigger: 'submit' }],
        vmCol: [{ required: true, message: '请输入', trigger: 'submit' }],
        channelMaxCapacity: [
          { required: true, message: '请输入', trigger: 'submit' }
        ],
        image: [{ required: true, message: '请输入', trigger: 'submit' }]
      }
    }
  },
  created () {
    this.searchTaskList()
  },
  methods: {
    cancel () {
      this.dialogFormVisible = false
      this.$refs.dialogForm.resetFields()
      this.TypeNewFrom = {
        name: '',
        model: '',
        vmRow: undefined,
        vmCol: undefined,
        channelMaxCapacity: undefined,
        image: ''
      }
    },
    // 每次更新获取售货机
    async searchTaskList () {
      this.loading = true
      const page = {
        pageIndex: this.TypeData.pageIndex,
        pageSize: this.TypeData.pageSize,
        name: this.searchForm.vmType
      }
      const { data } = await getVmTypeSearch({ ...page })
      // console.log(data)
      this.TypeData = data
      // console.log(this.TypeData.currentPageRecords)
      // console.log(this.TypeData)
      // 底部分页
      this.loading = false
    },
    // 售货机类型 新增 修改
    submitType () {
      this.$refs.dialogForm.validate(async (isOK) => {
        if (isOK) {
          try {
            if (this.showType) {
              await ChangeVmTypeDetial(this.TypeNewFrom)
            } else {
              await addVmType(this.TypeNewFrom)
            }
          } catch (e) {
            this.$message.warning(e.response.data)
          }
          this.$refs.dialogForm.resetFields()
          this.cancel()
          this.searchTaskList()
        }
      })
    },
    // 修改售货机
    async revampType (scope) {
      // const { data } = await getVmTypeDetial(scope.row.typeId)
      this.TypeNewFrom = scope.row
      console.log(this.TypeNewFrom)
      this.showType = true // true 显示修改
      this.dialogFormVisible = true
    },
    // 新增售货机
    addTypeClick () {
      this.dialogFormVisible = true
      this.showType = false
    },
    // 删除售货机
    async delType (typeId) {
      try {
        await delVmType(typeId)
      } catch (e) {
        this.$message.warning(e.response.data)
      }
      this.searchTaskList()
    },

    // 没有这个 会报错用来覆盖 action
    RequestImgType () {},
    // 自定义索引
    getIndex (index) {
      if (this.TypeData.pageIndex === '1') {
        return index + 1
      } else {
        return index + 10 * (this.TypeData.pageIndex - 1) + 1
      }
    },
    paginaTion (res) {
      // console.log(res)
      if (!this.loading) {
        if (res > this.TypeData.pageIndex) {
          this.TypeData.pageIndex++
          // 重新获取数据
          this.searchTaskList()
        } else {
          this.TypeData.pageIndex--
          this.searchTaskList()
        }
      }
    },
    handleAvatarSuccess (res, file) {
      this.image = URL.createObjectURL(file.raw)
    },
    async beforeAvatarUpload (file) {
      console.log(file)
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      const formData = new FormData()
      formData.append('fileName', file)
      const { data } = await updataImg(formData)
      this.TypeNewFrom.image = data
      console.log(this.TypeNewFrom.image)
      // this.RequestImgType(file)
      return isJPG && isLt2M
    }
  },
  computed: {
    getTotalCount () {
      return +this.TypeData.totalCount
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .dialog {
  width: 630px;
  .el-dialog__title {
    font-size: 16px;
  }
  .el-dialog__body {
    padding: 20px 40px;
    .el-form {
      padding-right: 20px;
    }
  }
  .el-input__inner {
    height: 36px;
    line-height: 36px;
  }
}
::v-deep.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 84px;
  height: 84px;
  line-height: 84px;
  text-align: center;
}
.avatar {
  width: 84px;
  height: 84px;
  display: block;
}
.el-icon-upload2 {
  font-size: 20px;
  color: #8c939d;
}
</style>
